package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author zlq
 * @CreateTime 2025/2/23
 */
@Component
@Slf4j
public class AccountReceiver {
    @Resource
    private UserAccountService userAccountService;

    //  bindings: 1. 在服务器内部实现队列与交换机的绑定关系!
    //  queues: 1. 当对于与交换机有绑定关系时，直接还用queues;
    @RabbitListener(bindings={
            @QueueBinding(
                    value=@Queue(value=MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
                    exchange = @Exchange(value=MqConst.EXCHANGE_USER),
                    key=MqConst.ROUTING_USER_REGISTER
            )
    })
    public void register(Long userId, Message message, Channel channel){
        System.out.println("用户注册成功！"+userId);
        //  消息在哪?
        byte[] body = message.getBody();
        System.out.println("消息内容：\t"+ new String(body).toString());
        System.out.println("Your消息内容：\t"+message.getMessageProperties().getDeliveryTag());

        try {
            //  判断
            if (null != userId){
                userAccountService.register(userId);
            }
        } catch (Exception e) {
            //  消费异常：
            System.out.println(e.getMessage());
            log.error(e.getMessage());
        }
        //  手动确认消息,保证消息从队列中出队; 否则会造成消息积压！ 表示是否是批量签收;
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
